package com.adee.java.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

public class RandomAccessFileTest {
    public static void main(String[] args) throws IOException {
        // write();
        write2();
    }
    // 从头写入文件，会覆盖原有内容
    public static void write() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
        raf.write(98);
        raf.close();
    }
    // 自定义位置写入文件
    public static void write2() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("raf2.txt", "rw");
        raf.seek(100); // 设置指针位置
        byte[] bytes = "hello raf".getBytes(StandardCharsets.UTF_8);
        raf.write(bytes); // 写入字节
        long p = raf.getFilePointer();
        System.out.println("当前指针位置：" + p);
        raf.seek(p + 10); // 空10字节
        raf.write("gagaga".getBytes(StandardCharsets.UTF_8));
        raf.close();
    }
}
